<template>
  <div class="edit-page-wrap">
    <Head title="优惠券信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="优惠券名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入优惠券名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="优惠券类型" prop="couponType">
            <qc-select
              :value="ruleForm.couponType"
              :options="optionsS.couponType"
              placeholder="请选择优惠券类型"
              @change="handleCheckType"
            >
            </qc-select>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.couponType === '0'"
            label="优惠券折扣"
            prop="discountRatio"
          >
            <el-input
              v-model.trim="ruleForm.discountRatio"
              placeholder="请输入优惠券折扣比例，正整数"
              maxlength="30"
              clearable
            >
              <template #append>%</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.couponType === '0'"
            label="折扣抵扣上限"
            prop="discountLimit"
          >
            <el-input
              v-model.trim="ruleForm.discountLimit"
              placeholder="请输入折扣抵扣上限"
              maxlength="30"
              clearable
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.couponType === '1'"
            label="优惠券面额"
            prop="discountAmount"
          >
            <el-input
              v-model.trim="ruleForm.discountAmount"
              placeholder="请输入优惠券面额"
              maxlength="30"
              clearable
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠券数量" prop="couponCount">
            <el-input
              v-model.trim="ruleForm.couponCount"
              placeholder="请输入优惠券数量"
              maxlength="9"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="承担方设置">
      <template #content>
        <Combination
          ref="comOrgRef"
          class="duty-wrap"
          :items="comItem"
          :comData="ruleForm.comData"
          :rules="comRules"
          :size="10"
        ></Combination>
      </template>
    </Head>
    <Head title="使用限制">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="抵扣费用类型" prop="discountType">
            <el-radio-group
              v-model="ruleForm.discountType"
              v-for="(item, index) in optionsS.couponDiscountType"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="qualifiedAmountLabel()" prop="qualifiedAmount">
            <el-input
              v-model.trim="ruleForm.qualifiedAmount"
              placeholder="请输入金额"
              maxlength="30"
              clearable
            >
              <template #prepend>满</template>
              <template #append>元可用</template>
            </el-input>
          </el-form-item>
          <el-form-item label="使用时间" prop="effectiveDateType">
            <el-radio-group
              v-model="ruleForm.effectiveDateType"
              v-for="(item, index) in optionsS.effectiveDateType"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.effectiveDateType === '0'"
            label="领取后"
            prop="effectiveDateLength"
          >
            <el-input
              v-model.trim="ruleForm.effectiveDateLength"
              placeholder="请输入相对时间"
              maxlength="3"
              clearable
            >
              <template #append>天</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.effectiveDateType === '1'"
            label="使用期限"
            prop="effectiveDate"
          >
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.effectiveDate"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>
          <el-form-item label="优惠券使用说明" prop="introduce">
            <el-input
              v-model.trim="ruleForm.introduce"
              placeholder="请输入优惠券使用说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="可用电站" prop="stationType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.stationType"
              v-for="(item, index) in optionsS.stationTargetType"
              :key="index"
              @change="handleStationType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{ stationTypeTip() }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.stationType === '1'"
            label=""
            prop="treeOrgs"
          >
            <QcTree
              ref="treeOrgRef"
              :setCheckedKeys="ruleForm.treeOrgs"
              :data="optionsS.org"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckOrg"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.stationType === '2'"
            label=""
            prop="treeStations"
          >
            <QcTree
              ref="treeStationRef"
              :setCheckedKeys="ruleForm.treeStations.split(',')"
              :data="optionsS.station"
              :showCheckbox="true"
              @handleCheck="handleCheckStation"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import Combination from '@/components/combination/combination.vue';
import { FormRules, FormInstance } from 'element-plus';
import { queryDicByParent } from '@/service/apis/api';
import {
  stationTreeDataByChannel,
  queryCarList,
  queryBusAndStation,
} from '@/service/apis/org';
import { saveActivity, getActivityById } from '@/service/apis/market';
import { IS_INT, IS_NUM_MORE0, IS_1_100 } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const comOrgRef = ref();
const treeOrgRef = ref();

const optionsS = reactive({
  couponType: [] as any,
  couponDiscountType: [] as any,
  effectiveDateType: [] as any,
  stationTargetType: [] as any,
  company: [] as any,
  org: [] as any,
  station: [] as any,
});

const orgId = window.localStorage.getItem('orgId') || '';
queryDicByParent({
  listDtos: [
    'couponType',
    'couponDiscountType',
    'effectiveDateType',
    'stationTargetType',
  ],
}).then((res: any) => {
  if (res) {
    optionsS.couponType = res.couponType;
    optionsS.couponDiscountType = res.couponDiscountType;
    optionsS.effectiveDateType = res.effectiveDateType;
    if (orgId) {
      optionsS.stationTargetType = res.stationTargetType.filter(
        (item: any) => item.value !== '0'
      );
      ruleForm.stationType = '1';
    } else {
      optionsS.stationTargetType = res.stationTargetType;
    }
  }
});

// 获取承担放
const getCompany = () => {
  queryBusAndStation({}).then((res: any) => {
    if (res) {
      optionsS.company = res.listMap;
      nextTick(() => {
        comOrgRef.value?.setOptions(0, 0, optionsS.company);
        comOrgRef.value?.setItemOption(optionsS.company, 0);
        if (id) {
          ruleForm.comData.forEach((item: any, index: number) => {
            comOrgRef.value?.setOptions(index, 0, optionsS.company);
          });
        }
      });
    }
  });
};

// 获取电站运营商树
const getOrgs = () => {
  queryCarList({}).then((res: any) => {
    if (res) {
      optionsS.org = res;
    }
  });
};

// 获取电站树
const getStations = () => {
  stationTreeDataByChannel({ cecType: 2 }).then((res: any) => {
    if (res) {
      optionsS.station = res;
    }
  });
};

const qualifiedAmountLabel = () => {
  if (ruleForm.discountType === '0') {
    return '订单总费用';
  } else if (ruleForm.discountType === '1') {
    return '订单服务费';
  } else if (ruleForm.discountType === '2') {
    return '订单电费';
  }
  return '';
};

const stationTypeTip = () => {
  if (ruleForm.stationType === '0') {
    return '所有电站均参与活动';
  } else if (ruleForm.stationType === '1') {
    return '选定运营商后，该运营商所有的电站均参与活动，含活动期间新增的电站';
  } else if (ruleForm.stationType === '2') {
    return '选定单电站后，仅所选电站参与活动，活动期间运营商新增电站不在活动范围内';
  }
  return '';
};

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};

const ruleForm: any = reactive({
  name: '', // 优惠券名称
  couponType: undefined as any, // 优惠券类型
  discountRatio: '', // 优惠券折扣
  discountLimit: '', // 折扣抵扣上限
  discountAmount: '', // 优惠券面额
  couponCount: '', // 优惠券数量

  dutyList: [], // 承担方列表
  comData: [],

  discountType: '1', // 抵扣费用类型
  qualifiedAmount: '', // 抵扣金额
  effectiveDateType: '0', // 使用时间
  effectiveDateLength: '', // 相对时间
  effectiveDate: [], // 绝对时间
  effectiveStartDate: null, // 有效开始时间
  effectiveEndDate: null, // 有效开始时间
  introduce: '', //优惠券使用说明
  stationType: '0', // 可用电站
  stationIds: '', //电站类型ids
  treeOrgs: [] as any, //限制站点数据-运营商-树
  treeStations: '', //限制站点数据-电站树
});

const checkDate = (rule: any, value: any, callback: any) => {
  if (
    Date.parse(value[1]) < new Date(new Date().toLocaleDateString()).getTime()
  ) {
    callback('使用期限结束时间不能小于当天');
  }
  callback();
};
const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  couponType: [
    {
      required: true,
      message: '请选择优惠券类型',
      trigger: ['blur', 'change'],
    },
  ],
  discountRatio: [
    { required: true, message: '请输入优惠券折扣', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正确的优惠券折扣比例，正整数',
      trigger: 'blur',
    },
  ],
  discountLimit: [
    { required: true, message: '请输入折扣抵扣上限', trigger: 'blur' },
    {
      pattern: IS_NUM_MORE0,
      message: '请输入正确的折扣抵扣上限，保留2位小数',
      trigger: 'blur',
    },
  ],
  discountAmount: [
    { required: true, message: '请输入优惠券面额', trigger: 'blur' },
    {
      pattern: IS_NUM_MORE0,
      message: '请输入正确的优惠券面额，保留2位小数',
      trigger: 'blur',
    },
  ],
  couponCount: [
    { required: true, message: '请输入优惠券数量', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正确的优惠券数量，正整数',
      trigger: 'blur',
    },
  ],
  discountType: [
    {
      required: true,
      message: '请选择抵扣费用类型',
      trigger: ['blur', 'change'],
    },
  ],
  qualifiedAmount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {
      pattern: IS_NUM_MORE0,
      message: '请输入正确的金额，保留2位小数',
      trigger: 'blur',
    },
  ],
  effectiveDateLength: [
    { required: true, message: '请输入相对时间', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正确的相对时间，正整数',
      trigger: 'blur',
    },
  ],
  effectiveDateType: [
    {
      required: true,
      message: '请选择使用时间',
      trigger: ['blur', 'change'],
    },
  ],
  effectiveDate: [
    {
      required: true,
      message: '请选择使用期限',
      trigger: ['blur', 'change'],
    },
    { validator: checkDate, trigger: 'change' },
  ],
  introduce: [
    { required: true, message: '请输入优惠券使用说明', trigger: 'blur' },
  ],
  stationType: [
    {
      required: true,
      message: '请选择可用电站',
      trigger: ['blur', 'change'],
    },
  ],
  treeOrgs: [
    { required: true, message: '请选择运营商', trigger: ['blur', 'change'] },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  treeStations: [
    { required: true, message: '请选择电站', trigger: ['blur', 'change'] },
  ],
});

const getCompanyLabel = () => {
  const arr = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
  arr.forEach((item: string, inx: number) => {
    arr[inx] = `承担方${item}`;
  });
  return arr;
};
const comItem = reactive([
  {
    comName: 'select',
    label: '承担方一',
    labels: getCompanyLabel(),
    labelWidth: 120,
    prop: 'orgId',
    width: 180,
    isOnly: true,
    props: {
      remote: true,
      filterable: true,
      options: optionsS.company,
    },
  },
  {
    comName: 'input',
    label: '承担比例',
    labelWidth: 70,
    prop: 'dutyRatio',
    width: 180,
    props: {
      append: '%',
      maxlength: 3,
      type: 'number',
      placeholder: '正整数',
    },
  },
]);

// const checkDutyRatio = (rule: any, value: any, callback: any) => {
//   const form = comOrgRef.value?.getData();
//   let num = 0;
//   form.forEach((item: any) => {
//     num += Number(item.dutyRatio);
//   });
//   if (num !== 100) {
//     comOrgRef.value?.setFlagAdd(false);
//     // callback(new Error('承担比例总和需要等于100'));
//   } else {
//     comOrgRef.value?.setFlagAdd(true);
//   }
//   callback();
// };
const comRules = reactive<FormRules>({
  orgId: [
    { required: true, message: '请选择承担方', trigger: ['blur', 'change'] },
  ],
  dutyRatio: [
    { required: true, message: '请输入承担比例', trigger: 'blur' },
    {
      pattern: IS_1_100,
      message: '请输入小于等于100的正整数',
      trigger: 'blur',
    },
    // { validator: checkDutyRatio, trigger: 'blur' },
  ],
});

const handleCheckType = (e: any) => {
  ruleForm.couponType = e;
};

const handleStationType = (val: any) => {
  if (val === '1' && optionsS.org.length === 0) {
    getOrgs();
  } else if (val === '2' && optionsS.station.length === 0) {
    getStations();
  }
};

const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.treeOrgs = checkedChildData;
};
const handleCheckStation = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeStations = checkedChildData.toString();
};

if (id) {
  getActivityById(id).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      ruleForm.couponType = String(res.couponType);
      ruleForm.discountType = String(res.discountType);
      ruleForm.effectiveDateType = String(res.effectiveDateType);
      ruleForm.effectiveDate = [res.effectiveStartDate, res.effectiveEndDate];
      ruleForm.stationType = String(res.stationType);
      //电站树
      if (ruleForm.stationType === '2') {
        ruleForm.treeStations = res.stationIds;
        getStations();
      } else if (ruleForm.stationType === '1') {
        ruleForm.treeOrgs = res.stationIds.split(',');
        getOrgs();
      }
      ruleForm.comData = [];
      res.dutyList.forEach((item: any) => {
        ruleForm.comData.push({
          orgId: item.orgId,
          dutyRatio: item.dutyRatio,
        });
      });
      getCompany();
    }
  });
} else {
  getCompany();
  if (orgId) {
    getOrgs();
  }
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
  }
  try {
    await Promise.all([comOrgRef.value.validate()]);
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key] && flag) {
        comOrgRef.value.scrollToField(key);
        break;
      }
    }
  }
  await Promise.all([
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef1.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  let num = 0;
  ruleForm.dutyList = [];
  const form = comOrgRef.value?.getData();
  form.forEach((item: any) => {
    ruleForm.dutyList.push({
      orgId: item.orgId,
      dutyRatio: item.dutyRatio,
    });
    num += Number(item.dutyRatio);
  });
  if (num !== 100) {
    ElMessage({
      showClose: true,
      message: '承担比例需要等于100%！',
      type: 'warning',
    });
    comOrgRef.value.scrollToField('data.[0][dutyRatio]');
    return;
  }
  // 使用时间
  if (ruleForm.effectiveDateType === '0') {
    ruleForm.effectiveStartDate = null;
    ruleForm.effectiveEndDate = null;
  } else if (ruleForm.effectiveDateType === '1') {
    ruleForm.effectiveDateLength = '';
    ruleForm.effectiveStartDate = ruleForm.effectiveDate[0];
    ruleForm.effectiveEndDate = ruleForm.effectiveDate[1];
  }
  // 电站树
  ruleForm.stationIds = '';
  if (ruleForm.stationType === '1') {
    // ruleForm.stationIds = ruleForm.treeOrgs;
    const arr: any = [];
    const treeOrg = treeOrgRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.stationIds = arr.toString();
  } else if (ruleForm.stationType === '2') {
    ruleForm.stationIds = ruleForm.treeStations;
  }
  // ruleForm.stationIds =
  //   ruleForm.stationType === '1'
  //     ? ruleForm.treeOrgs
  //     : ruleForm.stationType === '2'
  //     ? ruleForm.treeStations
  //     : '';

  // const form = comOrgRef.value?.getData();

  console.log('ruleForm----', ruleForm);
  saveActivity(ruleForm).then((res: any) => {
    emit('clear-cache');
    back();
  });
};
</script>

<style lang="scss" scoped>
.duty-wrap {
  :deep(.el-form-item:first-child) {
    .el-form-item__content,
    .el-form-item__error {
      padding-left: 24px !important;
    }
  }
}
</style>